package lumis.service.portalmanagement.channel;

import lumis.doui.control.inputtext.InputTextControl;
import lumis.doui.processaction.IProcessActionHandler;
import lumis.doui.source.ISourceData;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.channel.ChannelConfig;
import lumis.portal.channel.tree.IChannelChild;
import lumis.portal.channel.tree.IChannelChildProvider;
import lumis.portal.channel.tree.PageProvider;
import lumis.portal.manager.ManagerFactory;

/**
 *	Controls that shows the inherited page template 
 *	@version $Revision: 4263 $ $Date: 2006-09-06 11:29:27 -0300 (Wed, 06 Sep 2006) $
 *	@since 4.0.6
 */
public class ChannelInheritedPageTemplateControl extends InputTextControl 
{
	@Override
	public void setRenderData() throws PortalException
	{
		Source defaultSource = douiContext.getSourceContainer().getSourceById("default");
		ISourceData sourceData = defaultSource.getData();
		String parentChannelId = sourceData.get("parentId", String.class);
		String parentPageTemplateId = null;
		String pageTemplateName = null;
		if (parentChannelId == null)
			parentChannelId = douiContext.getRequest().getParameter("parentChannelId");
		if (parentChannelId != null)
			parentPageTemplateId = ManagerFactory.getChannelManager().getPageTemplateIdRecursively(douiContext.getRequest().getSessionConfig(), parentChannelId, douiContext.getTransaction());
		if (parentPageTemplateId != null)
		{
			pageTemplateName = getPageTemplateName(parentPageTemplateId);
		}
		setValue(pageTemplateName);
		
		super.setRenderData();
	}

	private String getPageTemplateName(String pageTemplateId) throws PortalException
	{
		IChannelChildProvider channelChildProvider = new PageProvider();
		String name = "";
		String parentId = null;
		
		try
		{
			if(pageTemplateId != null)
			{
				IChannelChild channelChild = channelChildProvider.getChannelChild(douiContext.getRequest().getSessionConfig(), pageTemplateId, douiContext.getTransaction());
				if(channelChild != null)
				{
					name = channelChild.getName();
					parentId = channelChild.getChannelId();
				}
			}
			
			while(parentId != null)
			{
				ChannelConfig channelConfig = ManagerFactory.getChannelManager().get(douiContext.getRequest().getSessionConfig(), parentId, douiContext.getTransaction());
				if(channelConfig != null)
				{
					name = channelConfig.getName() + "/" + name;
					parentId = channelConfig.getParentId();
				}
			}
		}
		catch (PortalObjectNotFoundException e)
		{
			name="";
			parentId = null;
		}		
		return name;
	}
	
	@Override
	public void setProcessActionHandlerParameters(IProcessActionHandler processActionHandler) throws PortalException
	{
	}

	@Override
	protected void autoAddValidators() throws PortalException
	{
	}
}
